<?php
include_once("ExtArray.php");

class DB
{
	// Private properties
	private $conn = null;
	private $host = null;
	private $user = null;
	private $pass = null;
	private $db = null;
	private $established = false;

	// .ctor
	public function __construct($config=null)
	{
		$this->get_config($config);
		$this->conn = mysql_connect($this->host, $this->user, $this->pass);
		mysql_select_db($this->db);
		$this->established = true;
	}

	// Executes SQL statement and returns whether it was successful
	public function execute($statement)
	{
		$result = mysql_query($statement, $this->conn) or die("Error: " . mysql_error());

		if($result)
			return true;
		return false;
	}
	
	// Executes SQL statement and returns result set as an array of rows
	public function execute_return($statement)
	{
		$result = mysql_query($statement, $this->conn) or die ("Error: " . mysql_error());
		$ret = array();

		while($row = mysql_fetch_assoc($result))
		{
			$ret[] = $row;
		}

		return $ret;
	}
	
	public function last_insert()
	{
		return mysql_insert_id($this->conn);
	}
	
	// Check to see if connection is established
	public function established()
	{
		return $this->established;
	}
	
	// Initializes the configuration from an external configuration file
	private function get_config($config=null)
	{
		if($config == null)
		{
			if(file_exists("inc/Config.php"))
				include_once("Config.php");
			else
				throw new Exception("Error: Config.php file missing");
		}
		else
		{
			include_once($config);
		}
		
		$this->host = HOST;
		$this->user = USER;
		$this->pass = PASS;
		$this->db = DB;
	}
}

class Select
{
	public $table;
	public $selectAll = false;
	public $fields;
	
	public function __construct()
	{
		$this->fields = new EArray();
	}
	
	public function out()
	{
		$select = "SELECT #ATTR# FROM `{$this->table}`;";
		$attrs = "";
		
		for($i = 0; $i < count($this->fields); $i++)
		{
			$attrs .= $this->fields[$i]->attr;
			
			if($i != count($this->fields) - 1)
				$attrs .= ", ";
		}
		
		return str_replace("#ATTR#", $attrs, $select);
	}
}

class Update
{
	public $table;
	public $fields;
	
	public function __construct()
	{
		$this->fields = new EArray();
	}
	
	public function out()
	{
		// Update person set whatever='1' where
		
		$update = "UPDATE `{$this->table}` SET #ATTR# WHERE;";
		$attrs = "";
		
		for($i = 0; $i < count($this->fields); $i++)
		{
			$attrs .= $this->fields[$i]->attr . "='" . $this->fields[$i]->val . "'";
			
			if($i != count($this->fields) - 1)
				$attrs .= ", ";
		}
		
		$update = str_replace("#ATTR#", $attrs, $update);
		return $update;
	}
}

class Field
{
	public $attr;
	public $val;
	
	public function attr($value)
	{
		$this->attr = $value;
		return $this;
	}
	
	public function val($value)
	{
		$this->val = $value;
		return $this;
	}
}


?>